const MYSQL = require("../../sql/mysql");
const sqlName = "verify_code";
const Dayjs = require("dayjs");
/**
 * 作废验证码
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
module.exports = async (params = {}) => {
  let { id, state } = params;
  if (!id) {
    throw { code: 500, msg: "作废失败,id不能为空" };
  } else if (!state) {
    throw { code: 500, msg: "作废失败,state不能为空" };
  }
  let updateQuery = `UPDATE ${sqlName} SET `;
  let date_now = Dayjs(Date.now()).valueOf();
  if (state == 0) {
    updateQuery += `state='${state}' `;
  } else if (state == 1) {
    throw { code: 500, msg: "作废失败,不支持将验证码作废为正常" };
  } else if (state == 2) {
    updateQuery += `state='${state}',verify_date = '${date_now}' `;
  } else if (state == 3) {
    updateQuery += `state='${state}',cancel_date = '${date_now}' `;
  } else {
    throw { code: 500, msg: "作废失败,不支持的作废类型" };
  }
  updateQuery += ` WHERE id = ${id}`;
  try {
    await MYSQL.Promise().query(updateQuery);
    return { code: 0, msg: "作废成功" };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "作废失败,在更新MYSQL记录时发生错误" };
  }
};
